<template>
    <view class="content">
        <view class="map-container">
            <view
                id="DzMap"
                :prop="sender"
                :change:prop="renderMaps.handleAction"
            ></view>
            <view class="map-control">
                <view class="zoom">
                    <view class="plus" @click="renderMaps.zoomIn">
                        <image src="@/static/img/map/jia.svg" class="icon" />
                    </view>
                    <view class="reduce" @click="renderMaps.zoomOut">
                        <image src="@/static/img/map/jian.svg" class="icon" />
                    </view>
                </view>
                <view class="recover df fdc ac" @click="handleRecoverFn">
                    <image src="@/static/img/map/recover.svg" class="icon" />
                    <view class="desc">恢复</view>
                </view>
                <view class="location df fdc ac" @click="goOrBackLocation">
                    <image src="@/static/img/map/dingwei.svg" class="icon" />
                    <view class="desc" v-if="nowView == 0">定位</view>
                    <view class="desc" v-else>复位</view>
                </view>
                <view
                    class="layer-choose df fdc ac"
                    @click="openlayerPopupShow"
                >
                    <image src="@/static/img/map/tuceng.svg" class="icon" />
                    <view class="desc">图层</view>
                </view>
                <view class="search df jc ac" @click="goToSearch">
                    <uv-icon name="search" />
                    <view>搜索</view>
                </view>
            </view>
            <view class="recover df fdc ac" @click="handleRecoverFn">
                <image src="@/static/img/map/recover.svg" class="icon" />
                <view class="desc">恢复</view>
            </view>
            <view class="location df fdc ac" @click="goOrBackLocation">
                <image src="@/static/img/map/dingwei.svg" class="icon" />
                <view class="desc" v-if="nowView == 0">定位</view>
                <view class="desc" v-else>复位</view>
            </view>
            <view class="layer-choose df fdc ac" @click="openlayerPopupShow">
                <image src="@/static/img/map/tuceng.svg" class="icon" />
                <view class="desc">图层</view>
            </view>
            <view class="search df jc ac" @click="goToSearch">
                <uv-icon name="search" />
                <view>搜索</view>
            </view>
        </view>
        <!-- <lhtabbar :activeIndex="1"></lhtabbar> -->
        <uv-popup ref="layerPopup" mode="right">
            <view class="layer-popup">
                <view class="bottom">
                    <h3>底图</h3>
                    <!-- <view class="name">底图</view> -->
                    <view
                        class="item"
                        @click="handleChooseLayerVisible('vector')"
                    >
                        <image
                            class="image"
                            src="@/static/img/map/tiandi.png"
                        />
                        <view class="desc">天地图</view>
                        <view class="chooseBtn" v-if="LayerMapName == 'vector'">
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                    <view
                        class="item"
                        @click="handleChooseLayerVisible('image')"
                    >
                        <image
                            class="image"
                            src="@/static/img/map/yingxiang.png"
                        />
                        <view class="desc">影像图</view>
                        <view class="chooseBtn" v-if="LayerMapName == 'image'">
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                </view>
                <view class="bottom">
                    <h3>地图显示</h3>
                    <view class="item">
                        <view
                            class="image"
                            @click="showPointLayer('fengxianqu')"
                        >
                            <image src="@/static/img/map/fengxianqu.png" />
                        </view>
                        <view class="desc">风险区</view>
                        <view
                            class="chooseBtn"
                            v-if="mapSelectList.includes('fengxianqu')"
                        >
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                    <view class="item">
                        <view
                            class="image"
                            @click="showPointLayer('qiepojianfang')"
                        >
                            <image src="@/static/img/map/qiepo.png" />
                        </view>
                        <view class="desc">切坡建房</view>
                        <view
                            class="chooseBtn"
                            v-if="mapSelectList.includes('qiepojianfang')"
                        >
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                    <view class="item">
                        <view
                            class="image"
                            @click="showPointLayer('hiddenPoint')"
                        >
                            <image src="@/static/img/map/yinhuandian.png" />
                        </view>
                        <view class="desc">隐患点</view>
                        <view
                            class="chooseBtn"
                            v-if="mapSelectList.includes('hiddenPoint')"
                        >
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                    <view class="item">
                        <view
                            class="image"
                            @click="showPointLayer('monitoring')"
                        >
                            <image src="@/static/img/map/jiancedian.png" />
                        </view>
                        <view class="desc">监测点</view>
                        <view
                            class="chooseBtn"
                            v-if="mapSelectList.includes('monitoring')"
                        >
                            <image src="@/static/img/map/dui.png" />
                        </view>
                    </view>
                </view>
                <!-- #ifdef H5 -->
                <uv-gap height="50px"></uv-gap>
                <!-- #endif -->
            </view>
        </uv-popup>

        <uv-popup
            ref="featurePopup"
            mode="bottom"
            closeable
            @change="hiddenFeaturePopup"
        >
            <view class="top-box">
                <view>{{ danType }}</view>
            </view>
            <view class="p-20">
                <uv-form
                    :model="popupInfo"
                    label-width="170rpx"
                    :labelStyle="{ fontSize: '28rpx' }"
                >
                    <uv-form-item label="名称:" borderBottom>
                        {{ popupInfo.name }}
                    </uv-form-item>
                    <uv-form-item label="编码:" borderBottom>
                        {{ popupInfo.code }}
                    </uv-form-item>
                    <uv-form-item label="地址:" borderBottom>
                        {{ popupInfo.site }}
                    </uv-form-item>
                    <!-- 监测点 -->
                    <uv-form-item
                        label="监测点类型:"
                        borderBottom
                        v-if="danType === '监测点'"
                    >
                        {{ popupInfo.monitoringtype || popupInfo.mold }}
                    </uv-form-item>
                    <!-- 监测点 -->
                    <uv-form-item
                        label="灾害类型:"
                        borderBottom
                        v-if="danType === '监测点'"
                    >
                        {{ popupInfo.disastertype || popupInfo.mold }}
                    </uv-form-item>
                    <!-- 切坡建房 -->
                    <uv-form-item
                        label="风险等级:"
                        borderBottom
                        v-if="danType === '切坡建房'"
                    >
                        {{ popupInfo.grade || popupInfo.riskLevel }}
                    </uv-form-item>
                </uv-form>
                <view class="btn-box">
                    <uv-button color="#1f87c6" @click="toBasic">
                        基本信息
                    </uv-button>
                    <uv-button
                        color="#1f87c6"
                        @click="toDetails"
                        v-if="danType === '监测点'"
                    >
                        监测设备
                    </uv-button>
                    <uv-button color="#1f87c6" @click="toMapAPP">
                        导航
                    </uv-button>
                </view>
            </view>
            <!-- #ifdef H5 -->
            <uv-gap height="50px"></uv-gap>
            <!-- #endif -->
        </uv-popup>
        <!-- 风险区 -->
        <uv-popup
            ref="featurePopupFxq"
            mode="bottom"
            closeable
            @change="hiddenFeaturePopup"
        >
            <view class="top-box">
                <view>{{ danType }}</view>
            </view>
            <view class="p-20">
                <uv-form
                    :model="popupInfo"
                    label-width="160rpx"
                    :labelStyle="{ fontSize: '28rpx' }"
                    v-if="xzBM == '430524'"
                >
                    <uv-form-item label="风险评:" borderBottom>
                        <!-- <uv-input :value="popupInfo['风险评']" readonly border="none" /> -->
                        {{ popupInfo['风险评'] }}
                    </uv-form-item>
                    <uv-form-item label="调查编:" borderBottom>
                        <!-- <uv-input :value="popupInfo['调查编']" readonly border="none" /> -->
                        {{ popupInfo['调查编'] }}
                    </uv-form-item>
                    <uv-form-item label="地址:" borderBottom>
                        <!-- <uv-input :value="popupInfo['乡镇'] + popupInfo['村']" readonly border="none" /> -->
                        {{ popupInfo['乡镇'] + popupInfo['村'] }}
                    </uv-form-item>
                </uv-form>
                <uv-form
                    :model="popupInfo"
                    label-width="160rpx"
                    :labelStyle="{ fontSize: '28rpx' }"
                    v-if="xzBM == '431382'"
                >
                    <uv-form-item label="风险评:" borderBottom>
                        <!-- <uv-input :value="popupInfo['风险等']" readonly border="none" /> -->
                        {{ popupInfo['风险等'] }}
                    </uv-form-item>
                    <uv-form-item label="调查编:" borderBottom>
                        <!-- <uv-input :value="popupInfo['BH']" readonly border="none" /> -->
                        {{ popupInfo['BH'] }}
                    </uv-form-item>
                    <uv-form-item label="地址:" borderBottom>
                        <!-- <uv-input :value="popupInfo['乡镇']" readonly border="none" /> -->
                        {{ popupInfo['乡镇'] }}
                    </uv-form-item>
                </uv-form>
                <uv-form
                    :model="popupInfo"
                    label-width="160rpx"
                    :labelStyle="{ fontSize: '28rpx' }"
                    v-if="xzBM == '431122'"
                >
                    <uv-form-item label="风险评:" borderBottom>
                        <!-- <uv-input :value="popupInfo['名称']" readonly border="none" /> -->
                        {{ popupInfo['名称'] }}
                    </uv-form-item>
                    <uv-form-item label="调查编:" borderBottom>
                        <!-- <uv-input :value="popupInfo['编号']" readonly border="none" /> -->
                        {{ popupInfo['编号'] }}
                    </uv-form-item>
                    <uv-form-item label="地址:" borderBottom>
                        <!-- <uv-input :value="popupInfo['地理位置']" readonly border="none" /> -->
                        {{ popupInfo['地理位置'] }}
                    </uv-form-item>
                </uv-form>
            </view>
            <!-- #ifdef H5 -->
            <uv-gap height="50px"></uv-gap>
            <!-- #endif -->
        </uv-popup>
    </view>
</template>
<!-- 逻辑层 -->
<script>
import {
    getAllCutSlopePoint_API,
    getAllHiddenDangerPoint_API,
    getAllMonitoringPoint_API,
    getHiddenMonitorAreaList_API,
} from '@/server/mapdzfz'
import { getLoginMsg } from '@/utils/util'
// import lhtabbar from '../lh-tabbar/lh-tabbar.vue'
// import data1 from "./data1.json";
// import data2 from "./data2.json";
// import data3 from "./data3.json";
const mapKeyList = {
    1: 'hiddenPoint',
    2: 'monitoring',
    3: 'qiepojianfang',
    4: 'quickpoint',
    5: 'xiangmu',
    6: 'fengxianqu',
}
export default {
    // components: { lhtabbar },
    data() {
        return {
            nowView: 0,
            sender: {
                handle: 'initMap', //调用视图层方法的名字
                callback: '', //回调函数的名字
                options: null, //传递给视图层的数据
                AdminCode: getLoginMsg()?.AdminCode,
            },
            xzBM: getLoginMsg()?.AdminCode,
            LayerMapName: 'vector',
            mapSelectList: [
                'fengxianqu', //风险区
                // "qiepojianfang", //切坡建房
                // "hiddenPoint", //隐患点
                // "monitoring", //监测点
            ],
            popupInfo: {},
            danType: '',
            // 防止重复请求监测点数据和隐患点数据
            isOnloadGetMonitoring: true,
            isOnloadGetHiddenPoint: true,
            //地图范围
            extentMoint: [],
            //当前缩放级别
            viewZoom: 10,
        }
    },
    onLoad() {
        const mapVal = uni.getStorageSync('map_key')
        // uni.hideTabBar()
        !mapVal && this.getAggregateLayer(0)
    },
    onShow() {
        try {
            const mapVal = uni.getStorageSync('map_key')
            if (mapVal) {
                const mapData = JSON.parse(mapVal)
                console.log('mapData:', mapData)
                let { lon, lat } = mapData
                if (!lon && !lat) {
                    return uni.showToast({
                        icon: 'error',
                        title: '错误的坐标格式！',
                    })
                }
                let lonReg =
                    /^-?(((\d|[1-9]\d|1[0-7]\d|0)\.\d{0,16})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,16}|180)$/i
                let latReg =
                    /^-?([0-8]?\d{1}\.\d{0,16}|90\.0{0,16}|[0-8]?\d{1}|90)$/i
                if (typeof lon == 'string') {
                    lon = Number(lon)
                }
                if (typeof lat == 'string') {
                    lat = Number(lat)
                }
                if (lonReg.test(lon) && latReg.test(lat)) {
                    const s = mapKeyList[mapData.pointtype]
                    console.log('s:', s)
                    this.mapSelectList = ['fengxianqu']
                    this.showPointLayer(s)
                    if (s === 'monitoring') this.isOnloadGetMonitoring = false
                    this.$nextTick(() => {
                        this.sendMsg(
                            'handleFitExtent',
                            '',
                            JSON.stringify({ data: mapData, type: s }),
                        )
                    })
                } else {
                    uni.showToast({
                        icon: 'error',
                        title: '错误的坐标格式！',
                    })
                }
            }
        } catch (error) {
            console.log('error:', error)
        }
    },
    methods: {
        /**
         * 逻辑层传递数据到视图层 类似父传子
         *
         * @param handle 触发视图层的方法名称
         * @param callback 视图层的方法名称（可选）暂时无用
         * @param options 消息发送的配置选项
         * @param rendCallback 逻辑层的回调函数（可选）暂时无用
         */
        sendMsg(handle, callback, options, rendCallback) {
            console.log('handle:', handle)
            this.sender = {
                handle,
                options,
                callback,
                rendCallback,
                AdminCode: getLoginMsg()?.AdminCode,
            }
        },
        /**
         * 视图层触发逻辑层方法 类似子传父
         * @param event callback 逻辑层的方法名称
         * @param event param 传递给逻辑层的数据
         */
        handleItemClick(event) {
            const handle = this[event.callback]
            handle && handle(event.param)
        },
        /**
         * 恢复
         */
        handleRecoverFn() {
            this.sendMsg('handlegoOrBackLocation', '', { type: 1 })
        },
        goOrBackLocation() {
            if (this.nowView === 0) {
                uni.showLoading({
                    title: '定位中...',
                })
                // #ifdef APP-PLUS
                plus.geolocation.getCurrentPosition(
                    (res) => {
                        const { latitude, longitude } = res.coords
                        this.sendMsg('handlegoOrBackLocation', '', {
                            type: 0,
                            latitude,
                            longitude,
                        })
                    },
                    (error) => {
                        console.error('Error getting location:', error.message)
                    },
                )
                // #endif
                // #ifdef H5
                navigator.geolocation.getCurrentPosition(
                    (res) => {
                        const { latitude, longitude } = res.coords
                        this.sendMsg('handlegoOrBackLocation', '', {
                            type: 0,
                            latitude,
                            longitude,
                        })
                    },
                    (error) => {
                        console.error('Error getting location:', error.message)
                    },
                )
                // #endif
                this.nowView = 1
                uni.hideLoading()
            } else {
                this.sendMsg('handlegoOrBackLocation', '', { type: 1 })
                this.nowView = 0
            }
        },
        goToSearch() {
            uni.navigateTo({
                animationType: 'slide-in-bottom',
                animationDuration: 200,
                url: '/pages/home/seach-item',
            })
        },
        openlayerPopupShow() {
            this.$refs.layerPopup.open()
        },
        handleChooseLayerVisible(type) {
            this.LayerMapName = type
            this.sendMsg('chooseLayerVisible', '', type)
        },
        async showPointLayer(type) {
            try {
                uni.showLoading({
                    title: '加载中',
                })
                //去重
                if (this.mapSelectList.includes(type)) {
                    this.mapSelectList = this.mapSelectList.filter(
                        (item) => item !== type,
                    )
                } else {
                    this.mapSelectList.push(type)
                    //处理初始化没有默认勾选点时 再次勾选需要请求接口
                    this.handleInitFistList(type)
                }
                this.sendMsg('handleShowPointLayer', '', this.mapSelectList)
            } finally {
                setTimeout(() => {
                    uni.hideLoading()
                }, 1000)
            }
        },
        /**
         * 第一次初始化接口数据时，才请求接口
         * @param type 类型，包括 "monitoring" 和 "hiddenPoint"
         */
        handleInitFistList(type) {
            switch (type) {
                case 'monitoring':
                    if (this.isOnloadGetMonitoring) {
                        this.getMonitorPoint()
                        this.isOnloadGetMonitoring = false
                    }
                    break
                case 'hiddenPoint':
                    if (this.isOnloadGetHiddenPoint) {
                        this.getHiddenDangerPoint(this.extentMoint)
                        this.isOnloadGetHiddenPoint = false
                    }
                    break
            }
        },
        /**
         * 获取监测点数据
         */
        async getMonitorPoint() {
            const res = await getAllMonitoringPoint_API()
            if (res.code === 0 && res.data.length > 0) {
                this.sendMsg('handleMonitorPoint', '', JSON.stringify(res.data))
            }
            // setTimeout(() => {
            //   this.sendMsg("handleMonitorPoint", "", JSON.stringify(data1));
            // }, 500)
        },
        /**
         * 视图层触发获取数据
         */
        async handleGetALlPoint(obj) {
            try {
                this.extentMoint = obj.data
                this.viewZoom = obj.zoom
                if (this.viewZoom < 10) return
                uni.showLoading({
                    title: '加载中',
                    mask: true,
                })
                console.log('范围:', this.extentMoint)
                console.log('zoom:', this.viewZoom)
                //初始化加载监测点数据

                if (
                    this.isOnloadGetMonitoring &&
                    this.mapSelectList.includes('monitoring')
                ) {
                    await this.getMonitorPoint()
                    //再次勾选监测点数据时，不再初始化加载
                    this.isOnloadGetMonitoring = false
                }

                //缩放 > 9 加载隐患点
                if (
                    this.viewZoom > 9 &&
                    this.mapSelectList.includes('hiddenPoint')
                ) {
                    await this.getHiddenDangerPoint()
                    this.isOnloadGetHiddenPoint = false
                }

                //缩放 >12 加载切坡建房数据
                if (
                    this.viewZoom > 12 &&
                    this.mapSelectList.includes('qiepojianfang')
                ) {
                    await this.getQpjfPoint()
                }
            } catch (error) {
                uni.hideLoading()
            } finally {
                uni.hideLoading()
            }
        },
        /**
         * 获取隐患点数据
         */
        async getHiddenDangerPoint() {
            const data = this.extentMoint
            const res = await getAllHiddenDangerPoint_API({
                latEnd: data[3],
                latStart: data[1],
                lonEnd: data[2],
                lonStart: data[0],
            })
            if (res.code === 0 && res.data.length > 0) {
                this.sendMsg('handleHiddenDanger', '', JSON.stringify(res.data))
            }
            // setTimeout(() => {
            //   this.sendMsg("handleHiddenDanger", "", JSON.stringify(data2));
            // }, 1000)
        },
        /**
         * 获取切坡建房数据
         */
        async getQpjfPoint() {
            const data = this.extentMoint
            const res = await getAllCutSlopePoint_API({
                latEnd: data[3],
                latStart: data[1],
                lonEnd: data[2],
                lonStart: data[0],
            })
            if (res.code === 0 && res.data.length > 0) {
                this.sendMsg('handleQpjfPoint', '', JSON.stringify(res.data))
            }
            // setTimeout(() => {
            //   this.sendMsg("handleQpjfPoint", "", JSON.stringify(data3));
            // }, 1500)
        },
        handleFeaturePopup(e) {
            this.danType = e.type || '监测点'
            console.log('danType:', e.type)
            const data = JSON.parse(e.data)
            this.popupInfo = data
            console.log('data:', data)
            switch (this.danType) {
                case '风险区':
                    this.$refs.featurePopupFxq.open()
                    break
                case '速报点':
                    this.popupInfo = {
                        ...this.popupInfo,
                        code: data.id,
                        site: data.name,
                    }
                    this.$refs.featurePopup.open()
                    break
                case '项目':
                    this.popupInfo = { ...this.popupInfo, code: data.id }
                    this.$refs.featurePopup.open()
                    break
                default:
                    this.$refs.featurePopup.open()
            }
        },
        // 前往详情及基本信息页面
        toBasic() {
            if (this.danType === '隐患点') {
                // 隐患点详情
                uni.navigateTo({
                    url:
                        '/pages/home/basic/dangerBasic?code=' +
                        this.popupInfo.code,
                })
            } else if (this.danType === '监测点') {
                // 监测点详情
                uni.navigateTo({
                    url:
                        '/pages/home/details/monitor?code=' +
                        this.popupInfo.code,
                })
            } else if (this.danType === '切坡建房') {
                // 切坡建房详情
                uni.navigateTo({
                    url:
                        '/pages/home/basic/cutSlopeBasic?code=' +
                        this.popupInfo.code,
                })
            } else if (this.danType === '速报点') {
                // 灾险情详情
                uni.navigateTo({
                    url:
                        '/pages/home/basic/disasterDanger?code=' +
                        this.popupInfo.code,
                })
            } else {
                // 项目详情
                uni.navigateTo({
                    url:
                        '/pages/home/basic/projectItem?code=' +
                        this.popupInfo.code,
                })
            }
        },
        toDetails() {
            uni.navigateTo({
                url: '/pages/home/details/device?jcode=' + this.popupInfo.code,
            })
        },
        //打开第三方地图
        toMapAPP() {
            let latitude = this.popupInfo.lat
            let longitude = this.popupInfo.lon
            let name = this.popupInfo.name
            let site = this.popupInfo.site
            let url = ''
            // #ifdef APP-PLUS
            if (plus.os.name == 'Android') {
                //判断是安卓端
                plus.nativeUI.actionSheet(
                    {
                        //选择菜单
                        title: '选择地图应用',
                        cancel: '取消',
                        buttons: [
                            {
                                title: '腾讯地图',
                            },
                            {
                                title: '百度地图',
                            },
                            {
                                title: '高德地图',
                            },
                        ],
                    },
                    function (e) {
                        switch (e.index) {
                            //下面是拼接url,不同系统以及不同地图都有不同的拼接字段
                            case 1:
                                //注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
                                url = `qqmap://map/marker?marker=coord:${latitude},${longitude};title:${name};addr:${site}&referer=RXFBZ-GSH63-VWR3W-3DG6U-3722H-Y2BQU`
                                break
                            case 2:
                                url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${site}&coord_type=gcj02&src=andr.baidu.openAPIdemo`
                                break
                            case 3:
                                url = `androidamap://viewMap?sourceApplication=creatar&poiname=${site}&lat=${latitude}&lon=${longitude}&dev=0`
                                break
                            default:
                                break
                        }
                        if (url != '') {
                            url = encodeURI(url)
                            //plus.runtime.openURL(url,function(e){})调起手机APP应用
                            plus.runtime.openURL(url, function (e) {
                                plus.nativeUI.alert('本机未安装指定的地图应用')
                            })
                        }
                    },
                )
            } else {
                // iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
                // 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
                //（如urlschemewhitelist:["iosamap","baidumap"]）
                plus.nativeUI.actionSheet(
                    {
                        title: '选择地图应用',
                        cancel: '取消',
                        buttons: [
                            {
                                title: '腾讯地图',
                            },
                            {
                                title: '百度地图',
                            },
                            {
                                title: '高德地图',
                            },
                        ],
                    },
                    function (e) {
                        switch (e.index) {
                            case 1:
                                url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=RXFBZ-GSH63-VWR3W-3DG6U-3722H-Y2BQU`
                                break
                            case 2:
                                url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`
                                break
                            case 3:
                                url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
                                break
                            default:
                                break
                        }
                        if (url != '') {
                            url = encodeURI(url)
                            plus.runtime.openURL(url, function (e) {
                                plus.nativeUI.alert('本机未安装指定的地图应用')
                            })
                        }
                    },
                )
            }
            // #endif

            // #ifdef H5
            uni.showActionSheet({
                itemList: ['百度地图', '高德地图', '腾讯地图'],
                success: function (res) {
                    console.log('选中了第' + (res.tapIndex + 1) + '个按钮')
                    let num = res.tapIndex + 1
                    if (num === 1) {
                        window.location.href = `http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${name}&content=超维地灾&output=html`
                    } else if (num === 2) {
                        window.location.href = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}`
                    } else if (num === 3) {
                        const mapUrl_tx =
                            'http://apis.map.qq.com/uri/v1/marker?marker=coord:' +
                            latitude +
                            ',' +
                            longitude +
                            ';title:' +
                            name +
                            ';addr:' +
                            name +
                            '&referer=yellowpage'
                        window.location.href = mapUrl_tx
                    }
                },
                fail: function (res) {
                    console.log(res.errMsg)
                },
            })
            // #endif
        },
        hiddenFeaturePopup(e) {
            this.sendMsg('handleFeaturePopupClose')
            if (!e.show) {
                uni.removeStorageSync('map_key')
            }
        },
        /**
         * 获取聚合的图层数据
         */
        async getAggregateLayer(type) {
            const res = await getHiddenMonitorAreaList_API({
                type,
                areaCode: this.xzBM,
            })
            if (res.code === 0 && res.data.length > 0) {
                this.sendMsg(
                    'handleAggregateLayer',
                    '',
                    JSON.stringify(res.data[0]),
                )
            }
        },
    },
}
</script>
<!-- 视图层 -->
<script module="renderMaps" lang="renderjs">
import DzMap from "@/map/index";
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
import { Select } from "ol/interaction";
import { getCityCode, getFxqByCode } from '@/map/json/district'
let map = null;
let mapLhJson = null
let selectInteraction = null
const LayerObj = {
	'fengxianqu': '风险区',
	'qiepojianfang': '切坡建房',
	'hiddenPoint': '隐患点',
	'monitoring': '监测点',
	'otherPoint':'详情图层',
	'quickpoint': '速报点',
	'xiangmu': '项目',
	'aggregate': '聚合图层'
}
// const otherLayerObj = {
// 	'quickpoint': '速报点',
// 	'xiangmu': '项目'
// }
export default {
	data() {
		return {
			AdminCode: '430524'
		};
	},
	mounted() {
        // #ifdef H5
		this.initMap();
        // #endif
	},
	methods: {
		handleAction(newValue, oldValue, ownerInstance, instance) {
			console.log('逻辑层传递过来的数据', JSON.stringify(newValue))
            if(newValue.AdminCode) this.AdminCode = newValue.AdminCode
			const handle = this[newValue.handle]
			let options = newValue.options
			// this.callback = newValue.callback
			if (!options) {
				options = undefined
			}
			if (!handle) {
				console.info('参数为标记需要执行的方法')
				return
			}
			handle(options)
		},
		initMap() {
			map = new DzMap("DzMap");
			mapLhJson = getCityCode(this.AdminCode);
			let features = map.format.converGeoJsonToFeature(mapLhJson.data);
			let geom = features[0].getGeometry();
			map.layer.initLayer(geom);
			// 更换层级
			let extent = geom.getExtent()
			map.map.getView().fit(extent, {
				duration: 0,//过渡时间
				padding: [10, 10, 10, 10]
			})
			// 添加图层
			for (const key in LayerObj) {
				map.layer.addLayers(LayerObj[key], 12)
			}
			// map.layer.addLayers("切坡建房", 12);
			// map.layer.addLayers("隐患点", 12);
			// map.layer.addLayers("监测点", 12);
			map.layer.addLayers("定位", 12)
			// this.handleInitList(extent)
			// 添加风险区图层
			this.handleFxqPolygon()
			// 添加缩放监听
			this.addMapEventListeners()
		    this.addSingleClick();
		},
		/**
		 * 触发逻辑层获取数据
		 */
		// handleInitList() {
		// 	const extent = map.map.getView().calculateExtent(map.map.getSize());
		// 	let currentZoom = map.map.getView().getZoom();
		// 	//取整数
		// 	currentZoom = Math.round(currentZoom)
		// 	// 如果小于9级，不触发回调函数
		// 	if (currentZoom < 9) return
		// 	this.$ownerInstance.callMethod('handleItemClick', {
		// 		callback: 'handleGetALlPoint',
		// 		param: {
		// 			data: extent,
		// 			zoom: currentZoom
		// 		}
		// 	})
		// },
		/**
		 * 添加地图事件监听（包括缩放和拖动）
		 */
		addMapEventListeners() {
			let eventTimer = null;
			let lastState = null;
			// 监听地图状态变化（包括缩放和拖动）
			map.map.on('moveend', (e) => {
				const currentZoom = Math.round(map.map.getView().getZoom());
				const currentCenter = map.map.getView().getCenter();
				const extent = map.view.calculateExtent(map.map.getSize());
				// 如果小于9级，不触发回调函数
				if (currentZoom < 9) return;

				// 创建当前状态对象
				const currentState = {
					zoom: currentZoom,
					center: currentCenter,
					extent: extent,
				};

				// 检查状态是否有显著变化
				if (lastState && this.isStateSimilar(lastState, currentState)) {
					return;
				}

				// 清除之前的定时器
				if (eventTimer) {
					clearTimeout(eventTimer);
				}

				// 设置防抖，1000ms后执行
				eventTimer = setTimeout(() => {
					console.log('地图状态变化:', currentState);
					this.$ownerInstance.callMethod('handleItemClick', {
						callback: 'handleGetALlPoint',
						param: {
							data: extent,
							zoom: currentState.zoom,
							// center: currentCenter,
						}
					});
					lastState = currentState;
				}, 1000);
			});
		},
		/**
		 * 检查两个状态是否相似
		 */
		isStateSimilar(state1, state2) {
			// 检查缩放级别
			if (state1.zoom !== state2.zoom) return false;

			// 检查中心点
			const [lon1, lat1] = state1.center;
			const [lon2, lat2] = state2.center;
			if (Math.abs(lon1 - lon2) > 0.001 || Math.abs(lat1 - lat2) > 0.001) {
				return false;
			}

			return true;
		},
		zoomIn() {
			let zoom = map.view.getZoom() + 1;
			map.view.animate({
				duration: 250,
				zoom,
			});
		},
		zoomOut() {
			let zoom = map.view.getZoom() - 1;
			map.view.animate({
				duration: 250,
				zoom,
			});
		},
		// 用户视图切换
		handlegoOrBackLocation(event) {
			if (event.type == 0) {
				const { latitude, longitude } = event;
				let geoJson = {
					"type": "FeatureCollection",
					"features": []
				}
				let feature = {
					type: "Feature",
					properties: {
						title: "用户坐标点"
					},
					geometry: {
						type: "Point",
						coordinates: [Number(longitude), Number(latitude)]
					}
				}
				geoJson.features.push(feature)
				// 转化为ol要素
				let features = map.format.converGeoJsonToFeature(geoJson)
				map.layer.addGenralPoint(features, "定位")
				// let img = require('@/static/img/map/position.svg')
				// 设置样式
				map.layer.setLayerIconStyle("定位", 'https://env-00jxt6hwsqjo.normal.cloudstatic.cn/lhmap/map/position.svg', .5)
				// 视图切换
				map.view.animate({
					center: [longitude, latitude],
					zoom: 12,
					duration: 1000
				})
			} else {
				let features = map.format.converGeoJsonToFeature(mapLhJson.data);
				let geom = features[0].getGeometry();
				// 更换层级
				let extent = geom.getExtent()
				map.map.getView().fit(extent, {
					duration: 300,//过渡时间
					padding: [10, 10, 10, 10]
				})
			}
		},
		chooseLayerVisible(type) {
			map.layer.changeBaseMap(type)
		},
		/**
		 * 切换 图层显示隐藏
		 */
		handleShowPointLayer(event = []) {
			if(!map) return
			let layers = map.map.getLayers().getArray();
			for (const key in LayerObj) {
				if (event.includes(key)) {
					map.layer.getLayerByName(LayerObj[key]).setVisible(true)
				} else {
					map.layer.getLayerByName(LayerObj[key]).setVisible(false)
				}
			}
		},
		//隐藏所有点图层
		// hideAllPointLayer(){
		//   	let layers = map.map.getLayers().getArray();
		//   	layers.forEach((layer) => {
		//     // 隐藏图层
		//     const l = LayerObj.includes(layer.get("layerName"))
		//     l && layer.setVisible(false)
		//   })
		// },
		handleMonitorPoint(newValue) {
			if (newValue === '' || newValue === undefined || newValue === null) return
			const l = JSON.parse(newValue)
			const jcdAllPoint = []
			// 过滤只保留隆回县区域内的监测点
			for (let i = 0; i < l.length; i++) {
				const item = l[i]
				if (item.code.indexOf(this.AdminCode) !== -1) {
					const point = [Number(item.lon), Number(item.lat)]
					const featurePoint = new Feature({
						geometry: new Point(point),
						...item,
						type: "监测点"
					})
					jcdAllPoint.push(featurePoint)
				}
			}
			// 添加到监测点图层
			map.layer.addJcdPoint(jcdAllPoint)
			// 默认设置监测点图层不可见
			// map.layer.getLayerByName("监测点").setVisible(true)
		},
		/**
		 * 获取隐患点数据
		 * @param newValue
		 */
		handleHiddenDanger(newValue) {
			if (newValue === '' || newValue === undefined || newValue === null) return
			const l = JSON.parse(newValue)
			const yhdAllPoint = []
			for (let i = 0; i < l.length; i++) {
				const item = l[i]
				if (item.code.indexOf(this.AdminCode) !== -1) {
					const point = [Number(item.lon), Number(item.lat)]
					const featurePoint = new Feature({
						geometry: new Point(point),
						...item,
						type: "隐患点"
					})
					yhdAllPoint.push(featurePoint)
				}
			}
			map.layer.addYhdPoint(yhdAllPoint)
		},
		/**
		 * 获取切坡点数据
		 */
		handleQpjfPoint(newValue) {
			if (newValue === '' || newValue === undefined || newValue === null) return
			const l = JSON.parse(newValue)
			const qpjAllPoint = []
			for (let i = 0; i < l.length; i++) {
				const item = l[i]
				if (item.code.indexOf(this.AdminCode) !== -1) {
					const point = [Number(item.lon), Number(item.lat)]
					const featurePoint = new Feature({
						geometry: new Point(point),
						...item,
						type: "切坡建房"
					})
					qpjAllPoint.push(featurePoint)
				}
			}
			map.layer.addQpjfPoint(qpjAllPoint)
		},
		/**
		 * 添加风险区图层
		 */
		handleFxqPolygon(newValue) {
            const fxq = getFxqByCode(this.AdminCode)
			let features = map.format.converGeoJsonToFeature(fxq.data)
			// 为风险区要素添加type属性
			features.forEach(feature => {
				feature.set('type', '风险区')
			})
			map.layer.addFxqPolygon(features)
		},
		/**
		 * 添加单点点击事件
		 */
		addSingleClick() {
			// 获取所有允许点击的图层
			let allowedLayers = []
			for (const key in LayerObj) {
				const layer = map.layer.getLayerByName(LayerObj[key])
				if (layer) {
					allowedLayers.push(layer)
				}
			}
			// 创建选择交互
			selectInteraction = new Select({
				layers: allowedLayers,
				style: null,
				// 添加点击容差，提高点击体验
				tolerance: 5
			})
			// 添加到地图
			map.map.addInteraction(selectInteraction)
			// 监听选中事件
			selectInteraction.on('select', (e) => {
				const feature = e.selected[0]
				if (feature) {
					const params = feature.getProperties()
					//触发逻辑层 handleFeaturePopup方法，并把参数传递过去
					this.$ownerInstance.callMethod('handleItemClick', {
						callback: 'handleFeaturePopup',
						param: {
							data: JSON.stringify(params),
							type: feature.get('type')
						}
					})
				}
			})
		},
		handleFeaturePopupClose() {
			console.log('清空选中状态')
			// 清空选中状态
			selectInteraction.getFeatures().clear()
		},
		/**
		 * 地图放大某个区域
		 */
		handleFitExtent(newValue) {
			if (newValue === '' || newValue === undefined || newValue === null) return
			const obj = JSON.parse(newValue)
			console.log("obj:", obj);
			const point = [Number(obj.data.lon), Number(obj.data.lat)]
			const type = LayerObj[obj.type]
			const featurePoint = new Feature({
				geometry: new Point(point),
				...obj.data,
				type
			})
			let extent = featurePoint.getGeometry().getExtent()
			map.layer.fitExtentPadding(extent, [150, 150, 150, 150],0, 16)
			if(type === '项目' || type === '速报点'){
				//添加点
				map.layer.addOtherPoint([featurePoint], type, obj)
	  		}
			this.handleFeaturePopupClose()
			this.$ownerInstance.callMethod('handleItemClick', {
				callback: 'handleFeaturePopup',
				param: {
					data: JSON.stringify(obj.data),
					type
				}
			})
		},
        handleAggregateLayer(newValue){
			if (newValue === '' || newValue === undefined || newValue === null) return
			const obj = JSON.parse(newValue)
			map.layer.addAggregateLayer(obj)
		}
	},
}
</script>
<style>
page {
    height: 100%;
}
</style>
<style lang="scss" scoped>
.content {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    :deep(.uv-icon__icon) {
        color: #ffffff !important;
        font-size: 36rpx !important;
    }
}

.map-container {
    position: relative;
    width: 100%;
    height: 100%;
    flex: 1;
    overflow: hidden;

    #DzMap {
        width: 100%;
        height: 100%;
    }

    .map-control {
        .zoom {
            position: absolute;
            top: 20rpx;
            left: 20rpx;
            padding: 10rpx;
            background-color: #fff;
            border-radius: 6rpx;

            .plus {
                padding-bottom: 6rpx;
                border-bottom: 1px solid gray;
            }

            .reduce {
                padding-top: 6rpx;
            }
        }

        .location {
            width: 70rpx;
            // padding: 6rpx;
            font-size: 24rpx;
            color: #1296db;
            position: absolute;
            bottom: 20rpx;
            left: 20rpx;
            background-color: #fff;
            border-radius: 6rpx;
        }

        .recover {
            width: 70rpx;
            // padding: 6rpx;
            font-size: 24rpx;
            color: #1296db;
            position: absolute;
            top: 20rpx;
            right: 20rpx;
            background-color: #fff;
            border-radius: 6rpx;
        }

        .layer-choose {
            position: absolute;
            right: 20rpx;
            bottom: 20rpx;
            background: #fff;
            width: 70rpx;
            padding: 6rpx;
            font-size: 24rpx;
            color: #1296db;
            border-radius: 6rpx;
        }

        .search {
            position: absolute;
            top: 20rpx;
            padding: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60%;
            height: 50rpx;
            border-radius: 10rpx;
            background-color: #fff;
            text-align: center;
            color: #999;
            font-size: 26rpx;
        }

        .icon {
            display: block;
            width: 40rpx;
            height: 40rpx;
        }
    }
}

.layer-popup {
    padding: 20rpx;
    height: 100%;
    overflow-y: auto;

    .bottom {
        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;

            .chooseBtn {
                width: 30rpx;
                height: 30rpx;
                position: absolute;
                right: 12rpx;
                top: 8rpx;

                image {
                    width: 100%;
                    height: 100%;
                }
            }

            .image {
                width: 90rpx;
                height: 90rpx;
                border-radius: 50%;
                margin-top: 20rpx;

                image {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}

.top-box {
    display: flex;
    padding: 20rpx;
    color: #ffffff;
    font-size: 28rpx;
    font-weight: bold;
    background-color: #1f87c6;
    justify-content: space-between;
}

.p-20 {
    padding: 20rpx;
}

.btn-box {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-around;

    .btn-bg {
        text-align: center;
        background-color: #1f87c6;
    }
}
</style>
